package com.msite.web;

import com.msite.framework.JsonResult;
import com.msite.model.SysUser;
import com.msite.service.SysUserService;
import com.msite.service.activiti.ActivitiService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by tpeng on 2016/4/15.
 */
@Controller
public class ActivitiController {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    HistoryService historyService;
    @Autowired
    ProcessEngine processEngine;

    @Resource
    private ActivitiService activitiService;
    @Resource
    private SysUserService sysUserService;

    /*@Autowired
    private ApplicantRepository applicantRepository;*/

    /**
     * 测试
     */
    @RequestMapping(value="/startMyProcess")
    @ResponseBody
    public String startMyProcess(@RequestParam("uid") Long uid) {
//        SysUser suser = sysUserService.selectByPrimaryKey(uid);
//        Map<String, Object> variables = new HashMap<String, Object>();
//        variables.put("suser", suser);
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myProcess")
                .latestVersion().active().singleResult();
//        ProcessInstance instance = runtimeService.startProcessInstanceByKey("myProcess", variables);
        ProcessInstance instance =
        runtimeService.startProcessInstanceById(definition.getId(), String.valueOf("uk_" + uid));

        SysUser suser = new SysUser();
        suser.setId(uid);
        suser.setSalt("1");
        sysUserService.updateByPrimaryKeySelective(suser);
        return "ok";
    }

    @RequestMapping(value="/approval")
    @ResponseBody
    public String approval(@RequestParam("uid") Long uid) {

        TaskService taskService = processEngine.getTaskService();

        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myProcess")
                .latestVersion().active().singleResult();

        List<HistoricProcessInstance> hpiList = historyService.createHistoricProcessInstanceQuery()
                .processDefinitionId(definition.getId())
                .processInstanceBusinessKey("uk_" + uid)
                .orderByProcessInstanceId()
                .desc()
                .list();
        if(hpiList == null || hpiList.isEmpty()){
            //("No process instance id found.");
            return "";
        }
        HistoricProcessInstance hpi = hpiList.get(0);
        String piInstanced = hpi.getId();

        Task task = taskService.createTaskQuery()
                .processInstanceId(piInstanced).active().singleResult();
        if(task != null) {
            taskService.complete(task.getId());
        }
        return "ok";
    }

    @RequestMapping(value = "/activiti/diagram/view_")
    public String diagram_page(ModelMap model, @RequestParam("uid") Long uid){
        String bussinessKey = "uk_" + uid;
        model.put("processKey", "myProcess");
        model.put("bussinessKey", bussinessKey);
        return "/diagram/diagram_view";
    }

    /**
     * 根据流程定义key 获取流程图资源
     * @param processKey
     */
    @RequestMapping(value = "/activiti/diagram/image")
    public void diagram_image(HttpServletResponse response, @RequestParam("processKey") String processKey) throws Exception{
        ProcessDefinition definition = activitiService.getProcessDefinitionByKey(processKey);
        if(definition == null){
            return;
        }
        String resourceName = definition.getDiagramResourceName();
        /*if (resourceType.equals("image")) {
            resourceName = definition.getDiagramResourceName();
        } else if (resourceType.equals("xml")) {
            resourceName = processDefinition.getResourceName();
        }*/
        InputStream imageStream = repositoryService.getResourceAsStream(
                definition.getDeploymentId(), resourceName);
        FileCopyUtils.copy(imageStream, response.getOutputStream());
    }

    /**
     * 根据业务定义key和流程定义key 获取该业务流程执行节点数据
     * @param processKey
     * @param bussinessKey
     * @return
     *
     */
    @RequestMapping(value = "/activiti/diagram/data")
    @ResponseBody
    public JsonResult diagram_data(@RequestParam("processKey") String processKey,
                                   @RequestParam("bussinessKey") String bussinessKey){
        Map<String, Object> actResMap = activitiService.getProcessTrace(processKey, bussinessKey);
        return new JsonResult(JsonResult.CODE_OK, "", actResMap);
    }


    /**
     * 展示流程图 高亮正在执行的节点.
     * return image stream
     */
    @RequestMapping(value="/showFlowImage")
    public void showFlowImage(HttpServletResponse response, @RequestParam("uid") Long uid) throws Exception{
        String processKey = "myProcess";
        String bussinessKey = "uk_" + uid;

        HistoricProcessInstance historicInstance = historyService.createHistoricProcessInstanceQuery()
                .processDefinitionKey(processKey)
                .processInstanceBusinessKey(bussinessKey)
                .singleResult();
        if(historicInstance == null){
            return;
        }
        BpmnModel bpmnModel = this.repositoryService.getBpmnModel(historicInstance.getProcessDefinitionId());
        /*List<HistoricActivityInstance> activityInstances = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(historicInstance.getId())
                .orderByHistoricActivityInstanceId().asc()
                .list();*/

        //得到正在执行的环节
        List<String> activeIds = this.runtimeService.getActiveActivityIds(historicInstance.getId());
        // 获得流程引擎配置
        ProcessEngineConfiguration processEngineConfiguration = processEngine
                .getProcessEngineConfiguration();
        String fontName = processEngine.getProcessEngineConfiguration().getActivityFontName();
        InputStream is = processEngineConfiguration.getProcessDiagramGenerator()
                .generateDiagram(bpmnModel, "png", activeIds, new ArrayList<String>(), fontName, fontName,
                        processEngineConfiguration.getClassLoader(), 1.0);

        response.setContentType("image/png");
        FileCopyUtils.copy(is, response.getOutputStream());
    }


}
